package com.gxgeek.springweb.filter.encrypt;

import com.alibaba.fastjson.JSON;
import com.gxgeek.springweb.model.DecryptDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author gaoxing
 * @create 2018-08-30 下午2:54
 */
@Slf4j
public class EncryptHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private String plainText = null;

    public EncryptHttpServletRequestWrapper(HttpServletRequest request, CryptoService cryptoService) {
        super(request);
        try {
            String s = IOUtils.toString(request.getInputStream(), "UTF-8");
            DecryptDTO decryptDTO = JSON.parseObject(s, DecryptDTO.class);
            String key = cryptoService.decrypt(decryptDTO.getB2());
            String sing  = request.getHeader("sing");

            String content = "";
            this.plainText = content;
//            this.plainText = IOUtils.toInputStream(content,"UTF-8");
//
//            byte[] requestBytes = IOUtils.toByteArray(request.getInputStream());
//            plainText = cryptoService.decrypt(new String(requestBytes, Charsets.UTF_8));
        } catch (Exception e) {
            log.error("failed to read from request input stream", e);
        }
    }

    @Override
    public String getContentType() {
        return "application/json";
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(plainText.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
